/*
 * Copyright (c) 2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.libermundi.tapestry.elfinder.pages;

import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.json.JSONObject;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.services.ajax.AjaxResponseRenderer;
import org.libermundi.tapestry.elfinder.JsonStreamResponse;
import org.libermundi.tapestry.elfinder.exception.ElFinderException;
import org.libermundi.tapestry.elfinder.services.ElFinderService;
import org.libermundi.tapestry.elfinder.services.MultipleUploadDecoder;
import org.slf4j.Logger;

/**
 * @author Martin Papy
 *
 */
public class ElFinderConnector {
	public static final String ELFINDER_EVENT="elfcmd";

	@Inject
	private Request _request;
	
	@Inject
	private ElFinderService _elFinderService;
	
	@Inject
	private Logger _logger;
	
    @Inject
    private AjaxResponseRenderer _ajaxResponseRenderer;
    
    @Inject
    private MultipleUploadDecoder _decoder;

	@OnEvent(value=ELFINDER_EVENT)
	public Object processCommand(){
		Object result;
		try{
			result = _elFinderService.processRequest(_request);
		} catch (ElFinderException e){
			_logger.error(e.getMessage(),e);
			result = error(e.getMessage());
		}
		if(_request.isXHR()){
			return result;
		}
		if(result instanceof JSONObject){
			return new JsonStreamResponse(result.toString()); 
		}
		return result;
	}

	/**
	 * @param string
	 * @return
	 */
	private JSONObject error(String msg) {
		return new JSONObject("error",msg);
	}

}
